#include "renderer/subrenderer.h"

#include <iostream>
#include "renderer/shader.h"

SubRenderer::SubRenderer(int width, int height, float frustumScale, float zNear, float zFar):width(width),height(height),frustumScale(frustumScale),zNear(zNear),zFar(zFar){
    for(unsigned int i=0;i<16;i++){
        perspectiveMatrix[i] = 0;
    }

    glGenSamplers(1, &sampler);
    glSamplerParameteri(sampler , GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glSamplerParameteri(sampler , GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glSamplerParameteri(sampler , GL_TEXTURE_MIN_FILTER , GL_LINEAR_MIPMAP_LINEAR);
    glSamplerParameteri(sampler , GL_TEXTURE_MAG_FILTER , GL_LINEAR);
}

std::shared_ptr<Shader> SubRenderer::GetShader(std::string name){
    if(shaders.find(name)!=shaders.end()){
        return shaders.find(name)->second;
    }
    else{
        std::cout<<"Shader not found: "<<name<<std::endl;
        return nullptr;
    }
}

void SubRenderer::InitialiseShaderProgram(std::string shaderName, std::vector<std::string> uniformList){
    std::shared_ptr<Shader> shader(new Shader(shaderName, uniformList));
    shaders.insert(std::pair<std::string,std::shared_ptr<Shader>>(shaderName, shader));
}

void SubRenderer::Resize(int w, int h){
    width = w;
    height = h;

    perspectiveMatrix[0] = frustumScale/(width/(float)height);
	perspectiveMatrix[5] = frustumScale;
	perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar);
	perspectiveMatrix[14] = (2 * zFar * zNear) / (zNear - zFar);
	perspectiveMatrix[11] = -1.0f;

    for(auto shader:shaders){
//        shader.second->SetUniform("perspectiveMatrix", 16, perspectiveMatrix);
    }
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
}
